package com.vx.ratingTool.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.vx.ratingTool.entities.Player;

@Repository
@Transactional(propagation = Propagation.REQUIRED)
public class PlayerDAO implements IPlayerDAO {

	private SessionFactory sessionFactory;

	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	private Session getSession() {
		return sessionFactory.getCurrentSession();
	}

	@Override
	public void save(Player player) {

		Session session = getSession();
		session.save(player);

	}

	@Override
	public void update(Player player) {

		Session session = getSession();
		session.update(player);

	}

	@Override
	public void delete(Player player) {

		Session session = getSession();
		session.delete(player);

	}

	@Override
	public Player findById(int id) {

		Session session = getSession();
		Player result = (Player) session.createQuery("from Player as p where p.id = :_id").setParameter("_id", id).uniqueResult();

		return result;
	}

	@Override
	public void saveList(List<Player> players) {

		Session session = getSession();
		for (int i = 0; i < players.size(); i++) {
			session.save(players.get(i));
		}

	}

	@Override
	public List<Player> getListOfPlayers() {

		Session session = getSession();
		List<Player> result = session.createQuery("from Player").list();
		return result;
	}

	@Override
	public void clearDatabase() {

		Session session = getSession();
		session.createQuery("delete Player").executeUpdate();

	}

	@Override
	public void massUpdate(List<Player> players) {

		Session session = getSession();
		for (int i = 0; i < players.size(); i++) {
			session.update(players.get(i));
		}

	}
}
